package com.kye.express.business.customer_intro.withdraw;

import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;

import com.kye.express.R;
import com.kye.express.business.login.LoginContract;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.RxView;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.SharedPreferencesConfig;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.customer_intro.CustomerIntroHistoryResultBean;
import com.kye.model.bean.customer_intro.GetOpenIdResultBean;
import com.kye.model.bean.customer_intro.GetSMSVerificationCodeResultBean;
import com.kye.model.bean.customer_intro.GetVerificationCodeResultBean;
import com.kye.model.bean.customer_intro.RequestCustomerIntroHistoryBean;
import com.kye.model.bean.customer_intro.RequestGetOpenIdBean;
import com.kye.model.bean.customer_intro.RequestGetSMSVerificationCodeBean;
import com.kye.model.bean.customer_intro.RequestGetVerificationCodeBean;
import com.kye.model.bean.customer_intro.RequestWithdrawBean;
import com.kye.model.bean.customer_intro.WithdrawResultBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.kye.model.service.CustomerIntroService;
import com.kye.model.service.UserService;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public interface CustomerIntroWithdrawActivityContract {

    interface CustomerIntroWithdrawActivityView extends RxView {
        Long GET_VERIFICATION_CODE_INTERVAL = 60L;
        String LAST_VERIFICATION_TIME = SharedPreferencesConfig.LAST_VERIFICATION_TIME_CUSTOMER_INTRO;

        void onComplete(boolean isLoadMore);

        void onLoading();

        void onLoaded(CustomerIntroHistoryResultBean datas, boolean isLoadMore);

        void onError(String msg, boolean isLoadMore);

        void onItemCheckChanged();

        void onCompleteGetOpenId();

        void onLoadedGetOpenId(GetOpenIdResultBean datas);

        void onErrorGetOpenId(String msg);

        void onErrorGetCode(String msg);

        void onLoadedGetCode(GetVerificationCodeResultBean datas);

        void onCountDown(Long seconds);

        void onGotSmsVerificationCode();

        void onCompleteWithDraw();

        void onLoadedWithDraw(WithdrawResultBean datas);

        void onErrorWithDraw(String msg);
    }

    class CustomerIntroWithdrawActivityViewPresenter extends BasePresenter<CustomerIntroWithdrawActivityContract.CustomerIntroWithdrawActivityView> {

        private int mCurrentPage = 1;
        private Context mContext;

        public CustomerIntroWithdrawActivityViewPresenter(Context context) {
            this.mContext = context;
        }

        /**
         * 初始化检查上次计时
         */
        public void checkNeedCountDown() {
            long current = SystemClock.uptimeMillis();
            long verificationTime = SharedPreferencesManager.get(CustomerIntroWithdrawActivityView.LAST_VERIFICATION_TIME, 0L);

            if (verificationTime <= current) return;

            getView().onCountDown((verificationTime - current) / 1000);
        }

        /**
         * 请求服务器数据
         *
         * @param isFirstIn  是否是刚进入页面请求数据，刚进入页面就需要显示loading view
         * @param isLoadMore true：加载下一页，false：刷新页面，加载第一页
         */
        public void loadDatas(final boolean isFirstIn, final boolean isLoadMore) {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(CustomerIntroService.class)
                    .getCustomerIntroHistory(new RequestCustomerIntroHistoryBean(phone, Constants.PAGE_SIZE, (isLoadMore ? (mCurrentPage + 1) : 1)))
                    .compose(getView().<OpenApiResult<CustomerIntroHistoryResultBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new OpenApiResultObserver<CustomerIntroHistoryResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            if (isFirstIn) {
                                getView().onLoading();
                            }
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_net_error), isLoadMore);
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete(isLoadMore);
                        }

                        @Override
                        public void onSuccess(OpenApiResult<CustomerIntroHistoryResultBean> result, CustomerIntroHistoryResultBean datas) {
                            if (!isLoadMore) {
                                resetPage();
                            }

                            if (datas != null) {
                                getView().onLoaded(datas, isLoadMore);
                                if (isLoadMore) {
                                    setCurrentPage(mCurrentPage + 1);
                                }
                            } else {
                                getView().onError(mContext.getString(R.string.common_no_more_datas), isLoadMore);
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<CustomerIntroHistoryResultBean> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onError(msg, isLoadMore);
                            } else {
                                getView().onError(mContext.getString(R.string.common_net_error), isLoadMore);
                            }
                        }
                    }));
        }

        public int getCurrentPage() {
            return mCurrentPage;
        }

        public void setCurrentPage(int currentPage) {
            this.mCurrentPage = currentPage;
        }

        public void resetPage() {
            setCurrentPage(1);
        }


        public void getOpenId() {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(CustomerIntroService.class)
                    .getOpenId(new RequestGetOpenIdBean(phone))
                    .compose(getView().<OpenApiResult<GetOpenIdResultBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new OpenApiResultObserver<GetOpenIdResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onErrorGetOpenId(mContext.getString(R.string.common_net_error));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onCompleteGetOpenId();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<GetOpenIdResultBean> result, GetOpenIdResultBean datas) {
                            if (datas != null) {
                                getView().onLoadedGetOpenId(datas);
                            } else {
                                getView().onErrorGetOpenId(mContext.getString(R.string.common_no_more_datas));
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<GetOpenIdResultBean> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onErrorGetOpenId(msg);
                            } else {
                                getView().onErrorGetOpenId(mContext.getString(R.string.common_net_error));
                            }
                        }
                    }));
        }

        public void getVerificationCode() {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(CustomerIntroService.class)
                    .getVerificationCode(new RequestGetVerificationCodeBean(phone))
                    .compose(getView().<OpenApiResult<GetVerificationCodeResultBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new OpenApiResultObserver<GetVerificationCodeResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onErrorGetCode(mContext.getString(R.string.customer_intro_get_verification_code_failed));
                        }

                        @Override
                        public void onLoaded() {
                        }

                        @Override
                        public void onSuccess(OpenApiResult<GetVerificationCodeResultBean> result, GetVerificationCodeResultBean datas) {
                            if (datas != null) {
                                getView().onLoadedGetCode(datas);
                            } else {
                                getView().onErrorGetCode(mContext.getString(R.string.customer_intro_get_verification_code_failed));
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<GetVerificationCodeResultBean> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onErrorGetCode(msg);
                            } else {
                                getView().onErrorGetCode(mContext.getString(R.string.customer_intro_get_verification_code_failed));
                            }
                        }
                    }));
        }

        public void getSmsVerificationCode(String imageVerificationCode) {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }
            RetrofitManager.getInstance()
                    .createOpenApiService(CustomerIntroService.class)
                    .getSMSVerificationCode(new RequestGetSMSVerificationCodeBean(phone, imageVerificationCode, "4"))
                    .compose(getView().<OpenApiResult<GetSMSVerificationCodeResultBean>>bindToLifecycleDestroy())
                    .doOnSuccess(new Consumer<OpenApiResult<GetSMSVerificationCodeResultBean>>() {
                        @Override
                        public void accept(OpenApiResult<GetSMSVerificationCodeResultBean> objectOpenApiResult) throws Exception {
                            SharedPreferencesManager.commit(CustomerIntroWithdrawActivityView.LAST_VERIFICATION_TIME, SystemClock.uptimeMillis() + CustomerIntroWithdrawActivityView.GET_VERIFICATION_CODE_INTERVAL * 1000);
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<GetSMSVerificationCodeResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                        }

                        @Override
                        public void onSuccess(OpenApiResult<GetSMSVerificationCodeResultBean> result, GetSMSVerificationCodeResultBean o) {
                            getView().onGotSmsVerificationCode();
                        }

                        @Override
                        public void onApiError(OpenApiResult<GetSMSVerificationCodeResultBean> result, int code, String msg) {
                            getView().onErrorGetCode(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onErrorGetCode(mContext.getString(R.string.customer_intro_get_sms_verification_code_failed));
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

        public void withDraw(String companys, String prices, String code) {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(CustomerIntroService.class)
                    .withDraw(new RequestWithdrawBean(companys, prices, phone, code))
                    .compose(getView().<OpenApiResult<WithdrawResultBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new OpenApiResultObserver<WithdrawResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onErrorWithDraw(mContext.getString(R.string.common_net_error));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onCompleteWithDraw();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<WithdrawResultBean> result, WithdrawResultBean datas) {
                            if (datas != null) {
                                getView().onLoadedWithDraw(datas);
                            } else {
                                getView().onErrorWithDraw(mContext.getString(R.string.common_net_error));
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<WithdrawResultBean> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onErrorWithDraw(msg);
                            } else {
                                getView().onErrorWithDraw(mContext.getString(R.string.common_net_error));
                            }
                        }
                    }));
        }
    }
}
